package io.github.yotta.common.api.model;


import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yotta
 * @date 2022/11/08 14:48
 */
@Data
public class Paging<T> implements Serializable {

    private Long totalPages;
    private List<T> data;
    private Long total;
    private Integer pageSize;
    private Integer pageNo;

    public Paging(Long total, List<T> data, Integer pageNo, Integer pageSize) {
        this.data = data;
        this.total = total;
        this.pageSize = pageSize;
        this.pageNo = pageNo;
        if (total > 0L && pageSize > 0) {
            long l = total % (long) pageSize;
            if (l == 0L) {
                this.totalPages = total / pageSize;
            } else {
                this.totalPages = total / pageSize + 1L;
            }
        } else {
            this.totalPages = 0L;
        }

    }

    public void ifNotEmpty(Consumer<T> consumer) {
        if (CollectionUtils.isNotEmpty(this.data)) {
            data.forEach(consumer);
        }
    }

    public <R> Paging<R> map(Function<T, R> function) {
        List<R> collect = Collections.emptyList();
        if (CollectionUtils.isNotEmpty(this.data)) {
            collect = this.data.stream().map(function).collect(Collectors.toList());
        }
        return new Paging<R>(this.total, collect, this.pageNo, this.pageSize);
    }

    public boolean hasNext() {
        return this.pageNo < this.totalPages;
    }
}
